import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, Modal, message, Space, Select, DatePicker } from 'antd';
import { addAuthList, delAllRole, delUserAuth, editUserAuth, getAcountList, getAuthList, getPositionTree, } from '@/services/demo/UserController';
import "./index.less";
import { ActionType, ProCard, ProTable } from '@ant-design/pro-components';
import Empower from '@/components/Empower';
import { EmpowerCode } from "@/../../code";
import dayjs from "dayjs";
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { useModel } from '@umijs/max';
import AuthButton from "@/components/AuthButton";
dayjs.extend(customParseFormat);

interface OptionType {
  label: string,
  key: string,
  code?: string,
  value?: string;
}

const dateFormat = "YYYY/MM/DD";
export default function Page() {
  const emRef = useRef<{ finish: any; }>();
  const [personOptions, setPersonOptions] = useState<OptionType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [model, contextHolder] = Modal.useModal();
  const tableRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalType, setModalType] = useState("新增");
  const [initialValues, setInitialValues] = useState({ status: 1 });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { initialState: { elements } } = useModel('@@initialState') as any;

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '授权人员',
      dataIndex: 'nickName',
      key: "nickName",
    },
    {
      title: '授权有效期',
      search: false,
      render: (user: API.AddAuthList) => dayjs(user.beginTime).format(dateFormat) + "到" + dayjs(user.endTime).format(dateFormat)
    },


    {
      title: '创建人',
      dataIndex: 'createName',
      search: false
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      search: false,
      valueType: "dateTime"
    },
    {
      title: '操作',
      fixed: 'right',
      search: false,
      render: (user: API.AddAuthList) => {

        return [
          <Button key="detail" size='small' type='link' onClick={() => accountDetail(user)}>详情</Button>,
          <AuthButton key="edit" size='small' type='link' permission={EmpowerCode['BTN_EDIT']} onClick={() => accountEdit(user)}>编辑</AuthButton>,
          <AuthButton key="delete" size='small' type='link' danger permission={EmpowerCode['BTN_DEL']} onClick={() => accountDelete(user.id!)}>删除</AuthButton>
        ];
      },
    },
  ];

  useEffect(() => {
    getAcountList({ page: 1, size: 999, param: {} }).then(res => {
      if (res.success) {
        const options = res.result.datas.map((data: any) => ({ label: data.nickName, value: data.id }));
        setPersonOptions(options);
      }
    });

  }, []);
  const selectChange = (keys: React.Key[]) => {
    setSelectedRowKeys(keys);
  };

  const onFinish = async () => {
    const params = { ...form.getFieldsValue(), ...emRef.current?.finish() };

    params.beginTime = params.custom[0].valueOf();
    params.endTime = params.custom[1].valueOf();

    let data;
    let text;
    if (modalType == "新增") {
      data = await addAuthList(params);
      text = "权限新增成功";
    } else if (modalType == "编辑") {
      data = await editUserAuth(params);
      text = "权限编辑成功";
    }
    const { success } = data;
    if (success) {
      tableRef.current?.reload();
      setIsModalOpen(false);
      message.success(text);
    }
  };

  const handleSubmit = () => {
    form.submit();
  };

  const accountAdd = () => {
    setIsModalOpen(true);
    setModalType("新增");
    form.resetFields();
  };
  const accountEdit = (user: API.AddAuthList) => {
    setIsModalOpen(true);
    form.setFieldsValue(user);
    form.setFieldValue("custom", [dayjs(user.beginTime), dayjs(user.endTime)]);
    form.setFieldValue("userIds", [user.userId]);
    console.log(form.getFieldsValue());

    setModalType("编辑");
  };
  const accountDetail = (user: API.AddAuthList) => {
    console.log(user);

    setIsModalOpen(true);
    form.setFieldsValue(user);
    form.setFieldValue("custom", [dayjs(user.beginTime), dayjs(user.endTime)]);
    form.setFieldValue("userIds", [user.userId]);
    setModalType("详情");
  };
  const delAccountList = () => {
    if (selectedRowKeys.length) {
      delAllRole(selectedRowKeys).then(res => {
        if (res.success) {
          message.success("批量删除成功");
          tableRef.current?.reload();
        }
      });
    } else {
      message.warning("请选中要删除的角色列表");
    }
  };
  const accountDelete = async (id: string) => {
    const confirmed = await model.confirm({ content: "确定删除?" });
    if (confirmed) {
      delUserAuth(id).then(res => {
        if (res.success) {
          message.success("删除成功");
          tableRef.current?.reload();
        }
      });
    }
  };

  return (
    <div>
      <ProCard split="vertical" style={{ height: "calc(100vh - 176px)" }}>
        <ProCard headerBordered style={{ height: "100%", overflowY: "auto" }}>
          <ProTable
            headerTitle={<Space style={{ marginBottom: "20px" }}>
              <AuthButton type='primary' permission={EmpowerCode['BTN_ADD']} onClick={accountAdd}>新增</AuthButton>
              <AuthButton permission={EmpowerCode['BTN_ALL_DEL']} onClick={delAccountList}>批量删除</AuthButton>
            </Space>}
            rowKey="id"
            options={false}
            actionRef={tableRef}
            cardBordered
            request={async (params) => {
              const { current, pageSize, typeId, nickName } = params;
              const { success, result: { datas, total } } = await getAuthList({ page: current!, size: pageSize!, param: { nickName } });

              return { data: datas, total, success };
            }}
            columns={columns}
            rowSelection={{ selectedRowKeys, onChange: selectChange }}
          />
        </ProCard>
      </ProCard>

      <Modal width="1200px" footer={(dom: React.ReactNode) => modalType == "详情" ? null : dom} className='account_modal' title={`角色 - ${modalType}`} maskClosable={false} open={isModalOpen} onOk={handleSubmit} onCancel={() => setIsModalOpen(false)} okText="提交"  >
        <Form size='large' labelCol={{ span: 4 }} form={form} disabled={modalType === "详情"} initialValues={initialValues} onFinish={onFinish}>
          <Form.Item
            name="id"
            hidden
          >
            <Input />
          </Form.Item>
          <Form.Item label="授权人员"
            name="userIds"

            rules={[{ required: true, message: '请输入授权人员' }]}
          >
            <Select
              disabled={modalType === "编辑"}
              mode={modalType === "编辑" ? undefined : "multiple"}
              placeholder={"请输入授权人员" + (modalType === "编辑" ? "" : "（多选）")}
              options={personOptions}
              optionFilterProp="label"
            />

          </Form.Item>

          <Form.Item label="授权有效期"
            name="custom"
            rules={[{ required: true, message: 'Please select 授权有效期' }]}>
            <DatePicker.RangePicker style={{ width: "100%" }} minDate={dayjs()} format={dateFormat} />
          </Form.Item>
          <Form.Item
            label="授权项"
            style={{ width: "100%" }}
            labelCol={{ span: 2 }}
            dependencies={["id"]}
          >
            {() => <Empower disabled={modalType === "详情"} ref={emRef} type={modalType === "编辑" ? "role" : "basic"} role={form.getFieldValue("id")}></Empower>}
          </Form.Item>
          <Form.Item
            label="备注"
            name="remark"
            style={{ width: "100%" }}
            labelCol={{ span: 2 }}
          >
            <Input.TextArea placeholder='请输入备注' allowClear autoSize={{ minRows: 3 }} showCount maxLength={500} />
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div >
  );
}


